package com.suixinsanren.design.observer.demo04;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WeatherStation implements Subject {

    private double maxTemperature;
    private double minTemperature;
    private double currentTemperature;
    private double humidity;
    private Date date;

    private final List<Observer> observers;
    private boolean isChanged;

    public WeatherStation() {
        observers = new ArrayList<>();
    }

    public void update(double maxTemperature, double minTemperature, double currentTemperature, double humidity, Date date) {
        this.maxTemperature = maxTemperature;
        this.minTemperature = minTemperature;
        this.currentTemperature = currentTemperature;
        this.humidity = humidity;
        this.date = date;
        setChanged();
        notifyObservers();
    }

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        if (isChanged) {
            observers.forEach(item ->
                    item.update(this.date, this.maxTemperature, this.minTemperature, this.currentTemperature, this.humidity));
        }
        cleanChanged();
    }

    @Override
    public void setChanged() {
        isChanged = true;
    }

    @Override
    public void cleanChanged() {
        isChanged = false;
    }


}
